package com.danielmiller.mygradebook;

import java.util.Locale;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddClass extends Activity {

	SQLiteDatabase db;
	EditText name, link;
	String nameString, linkString;
	int class_index;
	double overall = 0.0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.classname);
Log.d("TAG", "ERROR 1");
		name = (EditText)findViewById(R.id.class_name_edit_text);
		link = (EditText)findViewById(R.id.syllabus_edit_text);
Log.d("TAG", "ERROR 2");
		final Button createButton = (Button) findViewById(R.id.create_grade_rubric_button);
		createButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				nameString = name.getText().toString();
				linkString = link.getText().toString();
Log.d("TAG", "ERROR 3");
				db = openOrCreateDatabase(
						"SEMESTER_DB.db"
						, SQLiteDatabase.CREATE_IF_NECESSARY
						, null
				);
				db.setVersion(1);
				db.setLocale(Locale.getDefault());
				db.setLockingEnabled(true);
Log.d("TAG", "ERROR 4");
Log.d("TAG", "ERROR 5");
				String query = "INSERT INTO tbl_classes " +
					"VALUES (\"" + nameString + "\"," + overall + ",\"" + linkString + "\");";
				db.execSQL(query);
				
Log.d("TAG", "ERROR 6");
				//Toast
				Toast toast = Toast.makeText(getApplicationContext(), 
						"Class Saved!", Toast.LENGTH_SHORT);
				toast.show();
Log.d("TAG", "ERROR 7");
				Cursor cur = db.rawQuery("SELECT class_id FROM tbl_classes WHERE " +
						"class_name = '" + nameString + "'", null);
Log.d("TAG", "ERROR 8");
				if (cur != null ) {
					if (cur.moveToFirst()){
							class_index = Integer.parseInt(cur.getString(cur.getColumnIndex("class_id")));
					}
				}
Log.d("TAG", "ERROR 9");				

				db.close();

				Intent intent = new Intent(getBaseContext(), EditClassOverview.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("CLASS_INDEX", class_index);
				startActivity(intent);
Log.d("TAG", "ERROR 10");
			}
		});
	}
}